package lion.dev.text.charset;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.ByteOrderMarkDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.UnicodeDetector;

/***
 *
 * @author lion
 * @mail hl_0074@sina.com
 * @date 2011-12-27
 * @des 字符编码检测 需要 antlr,chardet,cpdetector三个jar
 */
public class MozillaCharsetDetector implements ICharsetDetect {

	private CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
	private static final String DEFAULT_CHARSET = "UTF-8";

	public MozillaCharsetDetector() {

		detector.add(new ByteOrderMarkDetector());
		detector.add(JChardetFacade.getInstance());
		detector.add(ASCIIDetector.getInstance());
		detector.add(UnicodeDetector.getInstance());
	}

	@Override
	public String detect(byte[] src) throws IOException {

		return detect(new ByteArrayInputStream(src));
	}

	@Override
	public String detect(InputStream src) {

		Charset charset = null;
		try {
			charset = detector.detectCodepage(src, 1024 * 5);
		} catch (Exception e) {
		}
		if (charset == null) { return DEFAULT_CHARSET; }

		if (StringUtils.equals(charset.name(), "windows-1252")) { return "GBK"; }
		return charset.name();
	}

	@Override
	public String detect(File src) {

		try {
			return detect(new FileInputStream(src));
		} catch (FileNotFoundException e) {
		}

		return DEFAULT_CHARSET;
	}
}
